package com.codeoss.framework.db.table;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.db.column.IColumnService;

@Service
public class MysqlTableService extends AbstractTableService {
	@Transactional
	public Object insert(YunContext yunContext, Table table, Map<String, Object> dataMap) {
		// TODO Auto-generated method stub
		
		dataMap.remove(table.getPrimaryKeyColumn().getColumnName());
		
		List<String> insertColumnList = new ArrayList<String>(dataMap.keySet());
		final String sql = getInsertSQL(table, insertColumnList);
		KeyHolder keyHolder = new GeneratedKeyHolder();
		
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
				// TODO Auto-generated method stub
				PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

				for (int i = 0; i < insertColumnList.size(); i++) {
					String columnName = insertColumnList.get(i);
					Column column = table.getColumnByColumnName(columnName);
					Object object = dataMap.get(columnName);
					IColumnService columnService = (IColumnService) applicationContext
							.getBean(column.getDataType() + "ColumnService");
					columnService.setValue(yunContext, column, ps, i + 1, object);
				}

				return ps;
			}

		}, keyHolder);
		return keyHolder.getKeys().get("GENERATED_KEY");
	}
	
	public String getPageSQL(YunContext yunContext, Table table, List<String> columnList, Query query) {
		String sql=getSelectSQL(yunContext, table, columnList, query);
		int offset=(query.getPage()-1)*query.getLimit();
		sql+=" limit "+query.getLimit()+" offset "+offset;
		return sql;
	}
}
